from webbrowser import get
from numpy import less
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options

import random
import os
import time
import logging
import socket
import pymysql
# import demjson
import pathlib
import sqlite3
logging.basicConfig(level=logging.INFO,format='%(asctime)s -%(levelname)s -%(process)d -%(module)s -%(funcName)s -%(message)s')
root=pathlib.Path(__file__).parent
sqlType="mysql" #sqlite
CorrectRate=0.85
userinfo=None
# sqlType="sqlite" 




if (sqlType=="mysql"):
    hostnamelist = ['192.168.2.247',"172.16.2.174","192.168.8.247"] #example
    for i in hostnamelist:
        response = os.system(f"ping -n 1 -w 500 {i}" )
        if response == 0:
            print(f"connect {i}")
            try:
                db = pymysql.connect(
                    host=i
                    ,user='xjzx'
                    ,password='Af1121113'
                    ,db='2class'
                    ,charset='utf8')
            except:
                print(f"mysql {i} connect error!")
                exit()
            break
        else:
            print (i, 'is down!')
elif(sqlType=="sqlite"):
    db=sqlite3.connect(str(root/"2_class.db"))

cur = db.cursor()
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
ipaddr=(s.getsockname()[0])
print(ipaddr)

def get_db(sql):
    cur.execute(sql)
    if (sqlType=="mysql"):
        return cur.fetchall()
    elif(sqlType=="sqlite"):
        r=cur.execute(sql)
        return r.fetchall()

global browser
def init():
    global browser
    # browser = webdriver.Firefox(firefox_binary=r"C:\Program Files\Mozilla Firefox\firefox.exe")
    ua = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36',
    # 创建浏览器选项对象
    options=Options()
    options.add_argument("--disable-blink-features")
    options.add_argument("--disable-blink-features=AutomationControlled")
    browser = webdriver.Chrome(options=options)
    url='https://www.2-class.com/'
    browser.get(url)
    browser.maximize_window()
    browser.implicitly_wait(15)
def findxpath(xpath,t=5):
    global browser
    browser.implicitly_wait(t)
    try:
        result = browser.find_element(By.XPATH,xpath)
    except :
        logging.info("not find xpath!")
        result= None

    return result
def findlinktext(text,t=5):
    global browser
    browser.implicitly_wait(t)
    try:
        result = browser.find_element(By.LINK_TEXT,text)
    except :
        logging.info("not find xpath!")
        result= None

    return result
def clickobj(obj):
    global browser
    actions = ActionChains(browser)
    actions.move_to_element(obj)
    actions.click(obj)
    actions.perform()
def _choice():
    title=findxpath('//*[@id="app"]/div/div[1]/div/div/div[1]/div[2]/div[1]/div')
    title=title.get_attribute('innerText')
    d={"A":1,"B":2,"C":3,"D":4}
    #title=title.replace("\n","")
    title=title.replace(" ","")
    title=title.replace("<br/>","")
    title=title.replace('\u3000',"")
    print(title)
    sql= "select questionAnswer from \"main\".\"2_class\" where \"questionTitle\" ='%s'"%(title)
    r=cur.execute(sql)
    t=r.fetchone()
    t=t[0]
    print(t)
    print(t[0])
    c=findxpath("/html/body/div/div/div[1]/div/div/div[1]/div[2]/div[2]/div/label[%d]/span[2]/div"%(d[t[0]]))
    c.click()
    # /html/body/div/div/div[1]/div/div/div[1]/div[2]/div[2]/div/label[1]/span[2]/div
    # /html/body/div/div/div[1]/div/div/div[1]/div[2]/div[2]/div/label[2]/span[2]/div
    # /html/body/div/div/div[1]/div/div/div[1]/div[2]/div[2]/div/label[3]/span[2]/div
def waitElement(xpath,waittime=10):
    global browser
    try:
        WebDriverWait(browser,waittime).until(EC.visibility_of_element_located((By.XPATH,xpath)))
    except:
        return False
    else:
        return True

def login(username="luoping6039",password="78102442"):
    login=findxpath("/html/body/div/div/div[1]/div/div/main/div[1]/div[1]/div/div[2]/div/button")
    clickobj(login)
    account=findxpath('//*[@id="account"]')
    pwd=findxpath('//*[@id="password"]')
    account.send_keys(username)
    pwd.send_keys(password)
    # account.send_keys('huangqi18400')
    # pwd.send_keys('71308315')
    login=findxpath("/html/body/div[2]/div/div[2]/div/div[1]/div/form/div/div/div/button")
    time.sleep(1)
    login.click()
    time.sleep(0.5)
    drag1=findxpath('//*[@id="nc_1_n1z"]')
    if (drag1 != None):
        action_chains = ActionChains(browser)
        action_chains.click_and_hold(drag1).perform()
        for i in range(3):
            action_chains.move_by_offset(120, 0).perform()
            time.sleep(random.random())
        # action_chains.drag_and_drop_by_offset(drag1, 360, 0).perform()
    d=findxpath("/html/body/div[2]/div/div[2]/div/div[1]/div/div/div[4]",2)
    if(d!=None):
        clickobj(d)
        time.sleep(1)

def c1():
    time.sleep(3)
    waitElement('//*[@id="app"]/div/div[1]/div/div/main/div[1]/div[1]/div/div[2]/span/a/button')
    qa=findxpath('//*[@id="app"]/div/div[1]/div/header/div/nav/ul/li[8]/a')
    qa.click()

    browser.execute_script('window.scrollTo(0,700)')

    

    f=findxpath("/html/body/div/div/div[1]/div/div/div[1]/div[2]/div[1]/div/div[1]/div[2]/p[1]/span",3)
    if(f != None):return False
    t=findxpath('//*[@id="app"]/div/div[1]/div/div/div[1]/div[2]/div/div[1]/button')
    t.click()
    browser.execute_script('window.scrollTo(0,700)')

    for i in range(19):
        _choice()
        ne=findxpath("//span[text()='下一题']",1)
        clickobj(ne)
    _choice()
    ne=findxpath("//span[text()='提 交']")
    clickobj(ne)

def c2(): #课时
    global browser
    lession = getjson("https://www.2-class.com/api/course/getMycourseList?state=all&pageNo=1&pageSize=4")
    lession= lession['data']['list']
    for i in lession:
        i= i['courseId']
        d=getjson(f"https://www.2-class.com/api/exam/getTestPaperList?courseId={i}")
        if ("testPaperList" in d['data'].keys()):
            browser.get(f"https://www.2-class.com/courses/exams/{i}")
            c=findxpath('//*[@id="app"]/div/div[1]/div/div/div/div[1]/div/button/span')
            clickobj(c)
            time.sleep(1)
            for n in d['data']['testPaperList']:
                answer=n['answer']
                answer=answer.split(",")
                for n in answer:
                    xpath=f'//*[@id="app"]/div/div[1]/div/div/div/div[1]/div/div[2]/label[{(int(n)+1):d}]'
                    c=findxpath(xpath)
                    clickobj(c)
                c=findxpath("//span[text()='下一题']",1) 
                if (c==None):  c=findxpath("//span[text()='提交']")
                clickobj(c) 
                time.sleep(1)

            



def getjson(url):
    global browser
    browser.get(url)
    time.sleep(0.5)
    t=browser.page_source
    t=t.replace("<html><head></head><body>","")
    t=t.replace("</body></html>","")
    t=demjson.decode(t)
    return t
def getanswer():
    d2=getjson("https://www.2-class.com/api/quiz/getQuizResultDetails") #竞赛答案
    for i in d2['data']["competitionQuestionBankDOList"]:
        print(i)

        cur.execute("Replace INTO class_answer(id, answerType, questionContent, questionTitle, questionAnswer) VALUES (%d,  \"%s\",\"%s\",\"%s\",\"%s\");"%(i['id'],i['answerType'],i['questionContent'],i['questionTitle'],i['answer']))
        # print("Replace INTO \"main\".\"class_answer\"(\"id\", \"answerType\", \"questionContent\", \"questionTitle\", \"questionAnswer\") VALUES (%d,  \"%s\",\"%s\",\"%s\",\"%s\");"%(i['id'],i['answerType'],i['questionContent'],i['questionTitle'],i['answer']))
    db.commit()
def findquestion():
    c=findxpath('//*[@id="app"]/div/div[1]/div/div/div[1]/div[2]/div[1]/div') #题目
    t=c.text.replace(" ","  ")
    t=t.replace("\n","\n<br>")
    print(t)
    r=get_db(f"select questionAnswer from class_answer where questionTitle = '{t}';")

    if(len(r)==0):
        return None
    else:
        return r[0][0]
def c3(): #竞赛
    t=getjson("https://www.2-class.com/api/growth/getMyBank") #课时
    if (t['data']==None): return t
    d1=getjson("https://www.2-class.com/api/quiz/isPass") #是否参加竞赛
    if(d1['data']==False):
        browser.get("https://www.2-class.com/competition")
        time.sleep(1)
        browser.execute_script('window.scrollTo(0,700)')
        c=findxpath("//*[@id=\"app\"]/div/div[1]/div/div/div[1]/div[2]/div/div[1]/button") #开始正式答题
        clickobj(c)
        li={'A':1,'B':2,'C':3,'D':4}
        time.sleep(0.1)
        
        for i in range(20):
            browser.execute_script('window.scrollTo(0,700)')
            time.sleep(0.3)
            q=findquestion()
            print(q)
            q=1 if q==None else li[q]
            if(random.random() > CorrectRate): 
                print("Adjustment error!")
                q=1 if q!=1 else 2
            c=findxpath(f'//*[@id="app"]/div/div[1]/div/div/div[1]/div[2]/div[2]/div/label[{q}]')
            clickobj(c)
            time.sleep(0.5)
            c=findxpath("//span[text()='下一题']",1)
            if(c==None):
                c=findxpath("//span[text()='提 交']")
                clickobj(c)
                break
            clickobj(c)
    time.sleep(1)
    d3=getjson("https://www.2-class.com/api/quiz/getQuizCertificate") #竞赛得分
    t['data']['point']=d3['data']['point']
    getanswer()
        # A  //*[@id="app"]/div/div[1]/div/div/div[1]/div[2]/div[2]/div/label[1]
        # B  //*[@id="app"]/div/div[1]/div/div/div[1]/div[2]/div[2]/div/label[2]
    # d4=getjson("https://www.2-class.com/api/quiz/getQuestionList?gradeType=七年级") #竞赛题目
    
    #https://www.2-class.com/api/quiz/isPass
    return t


if __name__ =="__main__":
    while 1:
        r=get_db("SELECT * FROM class_userinfo  where classhour is null LIMIT 0, 1")
        r=None if(len(r)==0) else r[0]

        # r=cur.execute("SELECT * FROM class_userinfo  where status = '0' LIMIT 0, 1")
        # r=cur.fetchone()
        if(r==None): 
            print("完成")
            break

        try:
            userinfo=r
            cur.execute("UPDATE class_userinfo SET classhour=-1 WHERE (id=%d)"%(r[0]))
            db.commit()
            init()
            login(r[3],r[4])
            c2()
            t=c3()
            # f=findxpath("/html/body/div/div/div[1]/div/div/div[1]/div[2]/div[1]/div/div[1]/div[2]/p[1]/span")
            # print(f.get_attribute('innerText'))
            if (t['data']==None):
                cur.execute("UPDATE class_userinfo SET classhour=-2 WHERE (id=%d)"%(r[0]))
            else:
                cur.execute("UPDATE class_userinfo SET classhour=%d WHERE (id=%d)"%(t['data']['classHour'],r[0]))
                if "point" in t['data'].keys() : 
                    cur.execute("UPDATE class_userinfo SET status=%d WHERE (id=%d)"%(t['data']['point'],r[0]))
            db.commit()
        except Exception as e:
            # print(e.msg)
            cur.execute("UPDATE class_userinfo SET classhour=-2 WHERE (id=%d)"%(r[0]))
            db.commit()

        finally:
            try:
                browser.close()
            except:
                pass


    a=input()
